#
# Optimizer.rb - Optimizes automata produced by Automaton.rb.
#

class Optimizer

  # Initializes the instance with the automaton arrays (ic, state1, state2) and
  # which state the matching should starting from.
  def initialize(ic, state1, state2, first_state)
    @ic = ic
    @state1 = state1
    @state2 = state2
    @first_state = first_state
  end

  attr_reader :ic, :state1, :state2 , :first_state
    
  # Applies the optimization.
  #
  # The optimization removes all unnecessary non-deterministic states to improve
  # matching performance.
  def ottimizza()
    i=0
    @ic.length.times do
      j=i
      if @ic[i] == '#' && @ic[i+1] == '#' && @state1[i] == @state2[i] && @state1[i] ==i+1 
         @ic.delete_at(i)
         @state1.delete_at(i)
         @state2.delete_at(i)
        
         if (@first_state >= i) 
          @first_state -= 1
         end
        
         k = 0
         while k<@ic.length do
          if @state1[k] > i
          @state1[k] -= 1
          end
           if @state2[k] > i
              @state2[k] -=1
           end
           k+=1
         end
      end
      i+=1
    end
  end
 
end
